package com.mdxq.mall.service;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class MinioService {

    @Autowired
    private MinioClient client;//minio客户端实例

    @Value("${minio.bucketName}")
    private String bucketName;// 保存文件的桶的名字

    private SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd");

    /**
     * 随机生成一个存储的对象名   由当天的日期 + / + UUID字符串 + 文件后缀
     * @param originalName  原始文件名
     * @return
     */
    private String randomObjectName(String originalName){
        StringBuilder builder=new StringBuilder();
        builder.append(format.format(new Date()));
        builder.append("/");//目录分割符
        builder.append(UUID.randomUUID());//随机的UUID做文件名
        builder.append(originalName.substring(originalName.lastIndexOf(".")));
        return builder.toString();
    }

    public String uploadFile(MultipartFile file) throws Exception{
        String objectName=randomObjectName(file.getOriginalFilename());//随机一个文件名
        InputStream in=file.getInputStream();//获取输入流
        PutObjectArgs putObjectArgs=PutObjectArgs
                .builder()
                .bucket(bucketName)
                .object(objectName)
                .contentType(file.getContentType())
                .stream(in, file.getSize(),-1)
                .build();
        client.putObject(putObjectArgs);
        in.close();
        return objectName;
    }
}

